package com.smartdio.mindtrain.core;

public class TrainTimer implements Runnable {

	static public boolean running = false;
	
	static public TrainTimer current =null;

	final static public int[] SECLEVEL = new int[] { 10, 5, 3 };

	private int sec;

	private ICountingReceiver receiver;
	
	private boolean canceling = false;
	/**
	 * @param sec
	 */
	public TrainTimer(int level,ICountingReceiver receiver) {
		super();
		if (level >= SECLEVEL.length) {
			level = SECLEVEL.length - 1;
		}
		this.sec = SECLEVEL[level];
		this.receiver=receiver;
	}

	@Override
	public void run() {
		 cancelPrevious();
		receiver.start();
		for(int i = 0;i<sec;i++){
			if(canceling)return;
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				break;
			}
			if(canceling)return;
			receiver.currentSec(i);
		}

		receiver.hide();
		current=null;
	}
	
	protected void cancelPrevious(){
		if(current!=null){
			current.canceling=true;
		}
		current =this;
	}

}
